// app.js

App({
  globalData: {
    userInfo: null,
    isLoggedIn: false,
    openid: null,
    theme: 'theme-green',
    font: 'font-default',
    layout: 'layout-list',
    navBarHeight: 0,
    statusBarHeight: 0,
    menuButtonHeight: 0,
    menuButtonWidth: 0
  },
  
  onLaunch() {
    // 初始化云环境
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力');
    } else {
      wx.cloud.init({
        env: 'cloud1-6gjewz7jf1fbf260',
        traceUser: true,
      });
      
      // 获取用户openid并初始化用户数据
      this.getOpenid();
    }
    
    // 检查登录状态
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.globalData.userInfo = userInfo;
      this.globalData.isLoggedIn = true;
    }
    
    // 初始化主题设置
    this.initTheme();
    
    // 获取系统信息
    const systemInfo = wx.getSystemInfoSync();
    // 胶囊按钮位置信息
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
    
    // 导航栏高度 = 状态栏高度 + 44
    this.globalData.navBarHeight = systemInfo.statusBarHeight + 44;
    this.globalData.statusBarHeight = systemInfo.statusBarHeight;
    this.globalData.menuButtonHeight = menuButtonInfo.height;
    this.globalData.menuButtonWidth = menuButtonInfo.width;
  },
  
  // 初始化主题设置
  initTheme() {
    // 从本地存储获取主题设置
    const theme = wx.getStorageSync('theme') || 'theme-green';
    const font = wx.getStorageSync('font') || 'font-default';
    const layout = wx.getStorageSync('layout') || 'layout-list';
    
    // 更新全局数据
    this.globalData.theme = theme;
    this.globalData.font = font;
    this.globalData.layout = layout;
    
    // 确保主题设置被保存
    wx.setStorageSync('theme', theme);
    wx.setStorageSync('font', font);
    wx.setStorageSync('layout', layout);
  },
  
  // 获取用户openid
  getOpenid() {
    const that = this;
    
    // 先检查本地存储是否有openid
    const openid = wx.getStorageSync('openid');
    if (openid) {
      this.globalData.openid = openid;
      // 检查用户数据是否存在
      this.checkUserData(openid);
      return;
    }
    
    // 调用云函数获取openid
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('云函数获取openid成功', res.result);
        const openid = res.result.openid;
        that.globalData.openid = openid;
        
        // 存储到本地
        wx.setStorageSync('openid', openid);
        
        // 检查用户数据是否存在
        that.checkUserData(openid);
      },
      fail: err => {
        console.error('云函数获取openid失败', err);
        wx.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        });
      }
    });
  },
  
  // 检查用户数据是否存在
  async checkUserData(openid) {
    try {
      // 导入userService模块，确保在云环境初始化后调用
      const userService = require('./services/userService');
      
      // 初始化用户数据
      await userService.initUserData({
        openid: openid,
        nickName: '厨房新用户' + openid.substring(openid.length - 4),
        avatarUrl: '/imgs/chef-hat.svg'
      });
    } catch (error) {
      console.error('初始化用户数据失败', error);
    }
  },
  
  // 微信登录
  wxLogin() {
    const that = this;
    return new Promise((resolve, reject) => {
      wx.login({
        success(res) {
          if (res.code) {
            resolve(res.code);
          } else {
            reject(res.errMsg);
          }
        },
        fail(err) {
          reject(err);
        }
      });
    });
  },
  
  // 检查是否已登录
  checkLoginStatus() {
    return this.globalData.isLoggedIn;
  },
  
  // 登录
  login(userInfo) {
    this.globalData.userInfo = userInfo;
    this.globalData.isLoggedIn = true;
    wx.setStorageSync('userInfo', userInfo);
  },
  
  // 登出
  logout() {
    this.globalData.userInfo = null;
    this.globalData.isLoggedIn = false;
    wx.removeStorageSync('userInfo');
    
    // 跳转到登录页
    wx.redirectTo({
      url: '/pages/login/login'
    });
  },
  
  // 更新主题
  updateTheme(theme) {
    // 更新全局数据
    this.globalData.theme = theme;
    
    // 保存到本地存储
    wx.setStorageSync('theme', theme);
    
    // 获取当前所有页面
    const pages = getCurrentPages();
    
    // 更新所有页面的主题
    pages.forEach(page => {
      if (page && page.setData) {
        page.setData({ theme });
      }
    });
  }
});
